package judesart.app.client.ui.pub.project;

import java.util.ArrayList;
import java.util.List;

import judesart.app.client.controller.ProjectController;
import judesart.app.client.controller.ProjectControllerAsync;
import judesart.app.client.facebook.FbUtil;
import judesart.app.client.ga.Tracker;
import judesart.app.client.ui.pub.layout.PublicMainLayout;
import judesart.app.domain.Project;
import judesart.app.domain.ProjectArtwork;
import judesart.app.domain.ProjectPhoto;
import judesart.app.domain.Sketch;

import com.allen_sauer.gwt.log.client.Log;
import com.extjs.gxt.ui.client.Style.Scroll;
import com.extjs.gxt.ui.client.data.BaseListLoader;
import com.extjs.gxt.ui.client.data.BeanModel;
import com.extjs.gxt.ui.client.data.BeanModelReader;
import com.extjs.gxt.ui.client.data.ListLoadResult;
import com.extjs.gxt.ui.client.data.ListLoader;
import com.extjs.gxt.ui.client.data.MemoryProxy;
import com.extjs.gxt.ui.client.event.Events;
import com.extjs.gxt.ui.client.event.Listener;
import com.extjs.gxt.ui.client.event.SelectionChangedEvent;
import com.extjs.gxt.ui.client.store.ListStore;
import com.extjs.gxt.ui.client.widget.Composite;
import com.extjs.gxt.ui.client.widget.Dialog;
import com.extjs.gxt.ui.client.widget.Html;
import com.extjs.gxt.ui.client.widget.LayoutContainer;
import com.extjs.gxt.ui.client.widget.ListView;
import com.google.gwt.dom.client.Style.Unit;
import com.google.gwt.user.client.History;
import com.google.gwt.user.client.rpc.AsyncCallback;
import com.google.gwt.user.client.ui.FlowPanel;
import com.google.gwt.user.client.ui.Image;
import com.google.gwt.user.client.ui.TabLayoutPanel;

public class ProjectPanel extends Composite {
    private final ProjectControllerAsync projectController = ProjectController.Util.getInstance();
    private Project project;
    private final Html htmlTitle;
    private final Html htmlDescription;
    private final ListView<BeanModel> listViewPhotos;
    private final List<ProjectPhoto> photos = new ArrayList<ProjectPhoto>();
    private final ListLoader<ListLoadResult<ProjectPhoto>> photosLoader;
    private final ListView<BeanModel> listViewSketches;
    private final List<Sketch> sketches = new ArrayList<Sketch>();
    private final ListLoader<ListLoadResult<Sketch>> sketchesLoader;
    private final ListView<BeanModel> listViewArtworks;
    private final List<ProjectArtwork> artworks = new ArrayList<ProjectArtwork>();
    private final ListLoader<ListLoadResult<ProjectArtwork>> artworksLoader;
    private final LayoutContainer mainPanel;
    private final Html htmlFbLike;
    private final TabLayoutPanel tabLayoutPanel;

    public ProjectPanel() {
        MemoryProxy<List<ProjectPhoto>> photosProxy = new MemoryProxy<List<ProjectPhoto>>(photos);
        photosLoader = new BaseListLoader<ListLoadResult<ProjectPhoto>>(photosProxy, new BeanModelReader());
        ListStore<BeanModel> photosStore = new ListStore<BeanModel>(photosLoader);
        photosLoader.load();

        MemoryProxy<List<Sketch>> sketchesProxy = new MemoryProxy<List<Sketch>>(sketches);
        sketchesLoader = new BaseListLoader<ListLoadResult<Sketch>>(sketchesProxy, new BeanModelReader());
        ListStore<BeanModel> sketchesStore = new ListStore<BeanModel>(sketchesLoader);
        sketchesLoader.load();

        MemoryProxy<List<ProjectArtwork>> artworksProxy = new MemoryProxy<List<ProjectArtwork>>(artworks);
        artworksLoader = new BaseListLoader<ListLoadResult<ProjectArtwork>>(artworksProxy, new BeanModelReader());
        ListStore<BeanModel> artworksStore = new ListStore<BeanModel>(artworksLoader);
        artworksLoader.load();

        mainPanel = new LayoutContainer();
        // mainPanel.setLayout(new RowLayout(Orientation.HORIZONTAL));
        mainPanel.setWidth("100%");
        mainPanel.setStyleAttribute("min-height", "600px");
        mainPanel.setBorders(false);
        mainPanel.setId("id-jaw-ProjectPanel");

        LayoutContainer leftPanel = new LayoutContainer();
        leftPanel.setSize("33%", "100%");
        leftPanel.setStyleAttribute("float", "left");
        // leftPanel.setLayout(new RowLayout(Orientation.VERTICAL));

        htmlTitle = new Html();
        htmlTitle.setTagName("h1");
        htmlTitle.setId("id-jaw-ProjectPanel-title");
        leftPanel.add(htmlTitle);

        htmlDescription = new Html();
        htmlDescription.setTagName("div");
        htmlDescription.setId("id-jaw-ProjectPanel-description");
        leftPanel.add(htmlDescription);
        htmlFbLike = new Html();
        htmlFbLike.setTagName("div");
        htmlFbLike.setId("id-jaw-ProjectPanel-fbLike");
        leftPanel.add(htmlFbLike);
        mainPanel.add(leftPanel);

        LayoutContainer rightPanel = new LayoutContainer();
        rightPanel.setSize("66%", "100%");
        rightPanel.setStyleAttribute("margin-top", "3em");
        rightPanel.setStyleAttribute("float", "right");
        mainPanel.add(rightPanel);

        tabLayoutPanel = new TabLayoutPanel(4, Unit.EM);
        tabLayoutPanel.setSize("600px", "600px");
        rightPanel.add(tabLayoutPanel);

        listViewPhotos = createListView(photosStore,
                "id-jaw-ProjectPanel-photos-list");
        FlowPanel container = new FlowPanel();
        container.add(listViewPhotos);
        container.getElement().setId("id-jaw-mycontainer-1");
        tabLayoutPanel.add(container, "Photos", false);

        listViewSketches = createListView(sketchesStore,
                "id-jaw-ProjectPanel-sketches-list");
        container = new FlowPanel();
        container.add(listViewSketches);
        container.getElement().setId("id-jaw-mycontainer-2");
        tabLayoutPanel.add(container, "Sketches", false);

        listViewArtworks = createListView(artworksStore,
                "id-jaw-ProjectPanel-artworks-list");
        container = new FlowPanel();
        container.add(listViewArtworks);
        container.getElement().setId("id-jaw-mycontainer-3");
        tabLayoutPanel.add(container, "Artworks", false);

        initComponent(mainPanel);
    }

    private ListView<BeanModel> createListView(ListStore<BeanModel> store,
            String id) {
        ListView<BeanModel> listView = new ListView<BeanModel>(store) {
            @Override
            protected BeanModel prepareData(BeanModel model) {
                if (model.getBean() instanceof ProjectArtwork) {
                    model.set("imageId",
                            ((ProjectArtwork) model.getBean()).getMainImageId());
                    model.set(
                            "description",
                            ((ProjectArtwork) model.getBean()).getMainImageTitle());
                }
                return model;
            }
        };
        listView.setLoadingText("loading...");
        listView.setBorders(false);
        listView.addStyleName("thumb-list");
        listView.setTemplate(getTemplate());
        listView.setItemSelector("div.thumb-wrap");
        listView.getSelectionModel().addListener(Events.SelectionChange,
                new Listener<SelectionChangedEvent<BeanModel>>() {
                    public void handleEvent(SelectionChangedEvent<BeanModel> be) {
                        onSelectionChanged(be);
                    }
                });
        listView.setId(id);
        return listView;
    }

    public void openProject(Long projectId) {
        projectController.getProject(projectId, new AsyncCallback<Project>() {

            @Override
            public void onSuccess(Project result) {
                setProject(result);
                PublicMainLayout.getInstance().loading(false);
            }

            @Override
            public void onFailure(Throwable caught) {
                Log.error("Unable to get project", caught);
                PublicMainLayout.getInstance().loading(false);
            }
        });
    }

    private void setProject(Project project) {
        this.project = project;
        htmlTitle.setHtml(this.project.getTitle());
        htmlDescription.setHtml(this.project.getDescription());
        String title = project.getTitle();
        String image = "http://www.judithshaylor.com/image/"
                + project.getPhotos().get(0).getImageId()
                + "_75x75_crop";
        String url = "http://www.judithshaylor.com/#project/" + project.getId();
        String description = project.getDescription();
        FbUtil.setOgMeta(getElement(), title, image, url, description);
        htmlFbLike.setHtml(FbUtil.like("project/" + project.getId()));
        photos.clear();
        if (this.project.getPhotos() != null) {
            photos.addAll(this.project.getPhotos());
        }
        int size = photos.size();
        photosLoader.load();
        sketches.clear();
        if (this.project.getSketchs() != null) {
            sketches.addAll(this.project.getSketchs());
        }
        if (sketches.size() > size)
            size = sketches.size();
        sketchesLoader.load();
        artworks.clear();
        if (this.project.getArtworks() != null) {
            artworks.addAll(this.project.getArtworks());
        }
        if (artworks.size() > size)
            size = artworks.size();
        int height = (size / 6 + 2) * 82;
        Log.debug(" > height [" + height + "]");
        if (height > 600)
            tabLayoutPanel.setHeight(height + "px");
        else
            tabLayoutPanel.setHeight("600px");
        artworksLoader.load();

        mainPanel.layout();
        FbUtil.parseFBML("id-jaw-ProjectPanel-fbLike");
    }

    private void onSelectionChanged(SelectionChangedEvent<BeanModel> be) {
        Object source = be.getSource();
        Log.debug("source [" + source + "]");
        if (be.getSelection().size() == 0) {
            return;
        }
        final BeanModel model = be.getSelection().get(0);
        if (model.getBean() instanceof ProjectArtwork) {
            History.newItem("gallery/artwork/"
                    + ((ProjectArtwork) model.getBean()).getArtworkId().toString());
        } else {
            Dialog dialog = new Dialog();
            dialog.setSize(960, 800);
            dialog.setScrollMode(Scroll.AUTO);
            Image image = new Image("/image/" + model.get("imageId")
                    + "_945x700");
            dialog.add(image);
            dialog.addText((String) model.get("description"));
            dialog.setBodyStyle("width: 100%; text-align: center; color: #999999;");
            dialog.setHideOnButtonClick(true);
            dialog.setButtons(Dialog.OK);
            dialog.show();
            Tracker.trackGoogleAnalytics("/project/" + project.getId() + "/image/" +  model.get("imageId"));
        }
        listViewPhotos.getSelectionModel().deselectAll();
    }

    private native String getTemplate() /*-{
        return ['<tpl for=".">', 
        '<div class="thumb-wrap" id="id-jaw-image-{imageId}">', 
        '<div class="thumb"><img src="/image/{imageId}_75x75_crop"/></div>',
        '</div>',
        '</tpl>', 
        '<!-- div class="x-clear"></div -->'
        ].join("");
    }-*/;

}
